import { useEffect, useRef, useState } from "react";
import { pokerOptions } from "../api";
import { Button, Card, message, Table, Tooltip, Modal, Popconfirm, Input, InputNumber } from "antd";
import RankingAward from "./RankingAward";
import { useLocation } from "react-router-dom";
import { doVote, pokerUserActivatInfoC, pokerUserActivatInfoIKing, selectGroup, userById } from "@/service";
import { getTimeDifference } from "@/utils";
import styles from './index.css'


export const ActiveDetail = () => {
  const [messageApi, contextHolder] = message.useMessage();
  const location = useLocation();
  const [jetton, setJetton] = useState(0);
  const [activateDesc, setActivateDesc] = useState(0);

  const [qqInfo, setQQInfo] = useState('');
  const [countDown, setCountDown] = useState<any>(); // 24 小时的秒数
  let timer: any = null;

  const [rankList, setRankList] = useState<any[]>([])
  const [cardInfo, setCardInfo] = useState<{
    taskId: string;
    activateId: string;
  }>({
    taskId: '',
    activateId: ''
  })
  const [userName, setUserName] = useState<any>(0);
  const [isModalOpen, setIsModalOpen] = useState(false);

  const [mainInfo, setMainInfo] = useState<{
    activateId: number;
    bianbianVal: number,
    groupName: string;
    id: number;
    kingName: string;
    isShowVote: number;
    rate: number;
    isJoin:number;
    teamVoteVOList: any[]
  }[]>([])

  const [activityId, setActivityId] = useState(0)
  const [activateList, setActivityList] = useState<any[]>([])
  const [voteItem, setVoteItem] = useState<any>(null)

  const [open, setOpen] = useState(false);
  useEffect(() => {
    (async () => {
      // 解析查询参数
      const queryParams = new URLSearchParams(location.search);
      const id = queryParams.get('id'); // 获取单个参数
      const taskId = queryParams.get('taskId');
      const endTime = queryParams.get('endTime');
      const activeName = queryParams.get('activeName');
      setCountDown(getTimeDifference(endTime))
      setQQInfo(activeName || '')
      console.log(id, 'idid');


      setCardInfo({
        taskId: taskId || '',
        activateId: id || '',
      })

      if (id) {
        getInfoDetail({ activateId: id })
      }
    })()

  }, [location.search]);


  useEffect(() => {
    getuserById()
  }, [])

  const getuserById = async () => {
    const res = await userById()
    console.log(res);
    setUserName(res?.username || 0)
  }


  const getInfoDetail = async (item: {
    activateId: string;
  }) => {
    const {activateDesc, groupTotalBianBian, kingTeamList } = await pokerUserActivatInfoIKing(item)
    setJetton(groupTotalBianBian || 0)
    setActivateDesc(activateDesc || 0)

    setMainInfo(kingTeamList || [])
    if (!activityId) {
      setActivityId(kingTeamList?.length > 0 ? kingTeamList[0]?.id : 0)
      setActivityList(kingTeamList?.length > 0 ? kingTeamList[0]?.teamVoteVOList : [])
    } else {
      const item = kingTeamList?.find((ele: any) => ele?.id === activityId)
      console.log(item, 'item');
      if (item) {
        setActivityId(item?.id || 0)
        setActivityList(item?.teamVoteVOList || [])
      }
    }
  }

  // const initData = async () => {
  //   setCountDown(60);
  // };
  // useEffect(() => {
  //   initData();
  // }, []);
  useEffect(() => {
    if (!countDown) return;
    clearInterval(timer);
    timer = setInterval(() => {
      setCountDown((prevCountDown: number) => {
        if (prevCountDown === 0) {
          clearInterval(timer); // 倒计时结束，清除定时器
          return 0;
        }
        return prevCountDown - 1; // 每秒减少 1 秒
      });
    }, 1000);

    // 清理定时器
    return () => clearInterval(timer);
  }, [countDown]);

  const confirm = async (item: any) => {

    const res = await selectGroup({
      activateId: cardInfo?.activateId,
      groupId: item?.id,
    })
    message.success(res)
    getInfoDetail({ activateId: cardInfo?.activateId || '' })
  }
  const bianbianNum = useRef(0)

  // 格式化倒计时为 HH:mm:ss
  const formatTime = (seconds: number) => {
    if (!seconds) return "00:00:00";
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    const s = seconds % 60;
    return `${String(h).padStart(2, "0")}:${String(m).padStart(
      2,
      "0"
    )}:${String(s).padStart(2, "0")}`;
  };

  const columns: any = [
    {
      title: "当前排名",
      dataIndex: "rank",
      key: "rank",
      align: "center",
    },
    {
      title: "玩家等级",
      dataIndex: "levelName",
      key: "levelName",
      align: "center",
    },
    {
      title: "玩家",
      dataIndex: "userName",
      key: "userName",
      align: "center",
    },
    {
      title: "支持便便",
      dataIndex: "bianbianVal",
      key: "bianbianVal",
      align: "center",
    },
  ];

  const selectRankingAward = () => {
    setOpen(true);
  };
  const handleOk = async () => {
    const value = bianbianNum.current;

    // 校验 bianbianVal 必须是大于 0 的数字
    if (!value || value <= 0) {
      message.warning('支持的便便必须大于0哦~');
      return;
    }

    try {
      const res = await doVote({
        activateId: cardInfo?.activateId,
        groupId: voteItem?.id,
        bianbianVal: value,
      });

      message.success(res);
      await getInfoDetail({ activateId: cardInfo?.activateId || '' });
      setIsModalOpen(false);
    } catch (error) {
      message.error('投票失败，请重试');
      console.error(error);
    }
  };

  const onChange = (value: number | null) => {
    bianbianNum.current = value || 0
  };

  return (
    <>
      <div className="activeDetail">
        {contextHolder}
        <div className="header">
          <Card>
            <div className="headerInfo">
              <div>活动便便池：{jetton}</div>
              <div>{qqInfo}</div>
              <div>活动结束倒计时：{formatTime(countDown)}</div>
            </div>
          </Card>
        </div>
        <div className="content">
          <Card
            title={
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8 }}>
                排名
                <div
                  className="selectRankingAward"
                  onClick={selectRankingAward}
                >
                  <Tooltip title="查看排名奖励">
                    <svg
                      className="icon"
                      viewBox="0 0 1066 1024"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg"
                      p-id="1504"
                      width="20"
                      height="20"
                    >
                      <path
                        d="M933.12 736l-115.626667-199.68a298.666667 298.666667 0 1 0-525.653333 0l-115.626667 199.68a42.666667 42.666667 0 0 0 37.12 64h122.453334l62.293333 104.96a42.666667 42.666667 0 0 0 7.68 9.386667 42.666667 42.666667 0 0 0 29.44 11.946666h5.973333a42.666667 42.666667 0 0 0 31.146667-20.906666L554.666667 763.733333l82.346666 142.933334a42.666667 42.666667 0 0 0 31.146667 20.48h5.973333a42.666667 42.666667 0 0 0 29.866667-11.946667 37.12 37.12 0 0 0 7.253333-8.96l62.293334-104.96H896a42.666667 42.666667 0 0 0 37.12-21.333333 42.666667 42.666667 0 0 0 0-43.946667z m-498.346667 65.28l-37.973333-63.573333a42.666667 42.666667 0 0 0-36.266667-20.906667H286.72l61.013333-105.813333a298.666667 298.666667 0 0 0 152.32 78.506666l-65.28 111.786667zM554.666667 608a213.333333 213.333333 0 1 1 0-426.666667 213.333333 213.333333 0 0 1 0 426.666667z m194.133333 108.8a42.666667 42.666667 0 0 0-36.266667 20.906667l-37.973333 63.573333-64.853333-113.066667a301.226667 301.226667 0 0 0 151.893333-78.506666l61.013333 105.813333-73.813333 1.28z"
                        fill="#42526E"
                        p-id="1505"
                      ></path>
                    </svg>
                  </Tooltip>
                </div>
              </div>
            }
            className="contentLeft"
          >
            <Table
              rowKey={(record, index) => record.id}
              dataSource={activateList}
              columns={columns}
              pagination={false}
              onRow={(record) => {
                if (record.userName === userName) {
                  return {
                    style: { background: '#00BFFF', color: 'black' }, // 红色背景+白色字体
                  };
                }
                return {};
              }}
            />
          </Card>
          <Card className="contentRight">
            <Card title="活动小标题" className="noticePoker" >
              <div className="noticeTitleList">
                {activateDesc}
              </div>
            </Card>
            <Card title="投票选项" className="playerPoker">
              <div className="playerPokerList1">
                {
                  mainInfo?.length > 0 && mainInfo?.map((item, index) => {
                    return <div key={index} className={`playerPokerItem ${activityId === item?.id ? 'activity' : ''}`} title="请点击查看排名" onClick={() => {
                      setActivityId(item?.id || 0)
                      setActivityList(item?.teamVoteVOList || [])
                    }}>
                      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flex: 1 }}>
                        <div style={{ flex: 2 }}>{item?.groupName || '--'}</div>
                        <div style={{ flex: 2 }}>最高支持者:    {item?.kingName || "暂无"}</div>
                        <div style={{ flex: 1 }}>{item?.rate * 100}%</div>
                      </div>
                      <div style={{ width: 100 }}>
                        <div>
                          {/* 只有 isJoin 为 1 才显示 加入 按钮 */}
                          {item.isJoin === 1 && (
                            <Popconfirm
                              placement="topLeft"
                              title={'确定加入吗？一旦加入不可更改'}
                              onConfirm={(e) => confirm(item)}
                              okText="确认"
                              cancelText="取消"
                            >
                              <a style={{ marginRight: 10, display: 'inline-block' }}>加入</a>
                            </Popconfirm>
                          )}

                          {/* 只有 isShowVote 为 1 才显示 投票 按钮 */}
                          {item.isShowVote === 1 && (
                            <a
                              style={{ marginRight: 10, display: 'inline-block' }}
                              onClick={() => {
                                setIsModalOpen(true);
                                setVoteItem(item);
                              }}
                            >
                              支持
                            </a>
                          )}
                        </div>
                      </div>
                    </div>
                  })
                }
              </div>
            </Card>
          </Card>
        </div>
      </div>
      <RankingAward open={open} setOpen={setOpen}
        activateId={cardInfo?.activateId} />
      <Modal title="支持" open={isModalOpen} onOk={handleOk} onCancel={() => setIsModalOpen(false)}
        footer={[
          <Button key="back" onClick={() => setIsModalOpen(false)}>
            取消
          </Button>,
          <Popconfirm key="submit" placement="topLeft" title="确认支持吗？" onConfirm={handleOk} okText="确认" cancelText="取消">
            <Button type="primary">
              确认
            </Button>
          </Popconfirm>
        ]}>
        <span>请输入支持的便便数量：</span><InputNumber onChange={onChange} />
      </Modal>
    </>
  );
};

export default ActiveDetail;
